package cn.cctvcc.security.service;

import cn.cctvcc.core.constant.cache.CachePrefixConstants;
import cn.cctvcc.core.constant.cache.CacheTimeOutConstants;
import cn.cctvcc.core.utils.IdUtils;
import cn.cctvcc.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: 一次性的令牌, 类似于门票, 用户先获取令牌, 然后在拿该令牌访问资源, 第一次访问资源后删除缓存令牌
 * @author: Jiang
 * @create: 2021-10-14 09:50
 */
@Component
public class SingleUseTokenService {

    private final static long EXPIRE_TIME = CacheTimeOutConstants.SINGLE_USE_EXPIRE;

    private final static String ACCESS_TOKEN = CachePrefixConstants.SINGLE_USE_KEY;

    @Autowired
    private RedisService redisService;

    /**
     * 创建令牌
     */
    public String createToken() {
        String token = IdUtils.fastUUID();
        redisService.setCacheObject(ACCESS_TOKEN + token, "", EXPIRE_TIME, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 校验令牌是否存在(如果删除失败则表示不存在令牌)
     */
    public boolean verifyToken(String token){
        if(redisService.deleteObject( ACCESS_TOKEN + token))
            return true;
        return false;
    }

}
